<template>
  <div class="coffee-origin">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="container">
        <router-link to="/" class="link">首页</router-link>
        <span class="sep">/</span>
        <span>咖啡分类</span>
      </div>
    </div>

    <main class="main">
      <div class="container">
        <h1 class="page-title">按产地选购咖啡豆</h1>

        <!-- 产地卡片 -->
        <div class="origin-grid">
          <div
            v-for="o in originCards.slice(0,4)"
            :key="o.id"
            class="origin-card"
            :data-category="o.id"
            @click="selectOrigin(o.id)"
          >
            <img
              :src="o.beantype_image
                ? (o.beantype_image.startsWith('http') ? o.beantype_image : `http://127.0.0.1:8000/static/${o.beantype_image}`)
                : ''"
              style="border-radius: 10px; width: 100%; height: 220px; object-fit: cover;"
              :alt="o.name"
            />
            <div class="card-overlay"></div>
            <div class="card-content">
              <h3>{{ o.name }}</h3>
            </div>
          </div>
        </div>

        <!-- 两栏布局 -->
        <div class="main-content">
          <!-- 左侧筛选 -->
          <aside class="filter-panel">
            <div class="filter-section">
              <h3>更多分类</h3>
              <button
                class="filter-btn"
                :class="{ active: currentOrigin === 'all' }"
                @click="changearea('all')"
              >
                全部产品
                <span class="badge">{{ totalProductCount }}</span>
              </button>
              <button
                v-for="c in originCards"
                :key="c.id"
                :class="['filter-btn', { active: currentOrigin === c.id }]"
                @click="changearea(c.id)"
              >
                {{ c.name }}
                <span class="badge">{{ c.productCount || 0 }}</span>
              </button>
            </div>
          </aside>

          <!-- 右侧列表 -->
          <section class="product-area">
            <div class="intro-bar">
              <h2>{{ currentTitle }}</h2>
              <p class="desc">{{ currentdescription }}</p>

              <div class="sort-bar">
                <span>排序方式：</span>
                <button
                  v-for="s in sortOptions"
                  :key="s.value"
                  :class="['sort-btn', { active: currentSort === s.value }]"
                  @click="currentSort = s.value"
                >
                  {{ s.label }}
                </button>
                <span class="spacer"></span>
                <button class="view-btn active"><i class="fa fa-th-large"></i></button>
                <button class="view-btn"><i class="fa fa-list"></i></button>
              </div>
            </div>

            <!-- 商品网格 -->
            <div class="product-grid">
              <div v-if="!Products.length && !loading" class="empty-tip">
                暂无该分类下的商品
              </div>
              <div v-if="loading" class="loading-tip">
                加载中...
              </div>
              <div
                v-for="p in displayedProducts"
                :key="p.id"
                class="product-card"
              >
                <div class="img-box">
                  <img
                    :src="p.image_urls && p.image_urls.length
                      ? `http://127.0.0.1:8000/static/${p.image_urls[0]}`
                      : ''"
                    :alt="p.name"
                    class="product-img"
                    style="height: 180px; object-fit: cover;"
                  />
                  <span v-if="p.is_recommend" class="badge featured">精选</span>
                  <div class="hover-box">
                    <router-link :to="'/productdetail?id=' + p.id" target="_blank">
                      <button class="icon-btn"><i class="fa fa-eye"></i></button>
                    </router-link>
                    <button class="icon-btn" @click="addToCart(p)"><i class="fa fa-shopping-cart"></i></button>
                    <button class="icon-btn" @click="addTofavorite(p)"><i class="fa fa-heart-o"></i></button>
                  </div>
                </div>

                <div class="card-body">
                  <div class="meta">咖啡 · {{ p.brand || '官方' }}</div>
                  <router-link :to="'/productdetail?id=' + p.id">
                    <div class="name">{{ p.name }}</div>
                  </router-link>
                  <div class="rating">
                    <i v-for="i in 5" :key="i" :class="starCls(i, p.stars || 5)"></i>
                    <span>({{ p.review_count || 0 }})</span>
                  </div>
                  <div class="price-row">
                    <span class="price">¥{{ p.price }}</span>
                    <span v-if="p.original_price" class="original">¥{{ p.original_price }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 分页 -->
            <div class="pagination" v-if="totalPages > 0">
              <button
                class="pagination-btn"
                @click="prevPage"
                :disabled="currentPage === 1 || loading"
              >
                上一页
              </button>
              <button
                v-for="page in totalPages"
                :key="page"
                class="pagination-page"
                :class="{ 'active': currentPage === page }"
                @click="goToPage(page)"
                :disabled="loading"
              >
                {{ page }}
              </button>
              <button
                class="pagination-btn"
                @click="nextPage"
                :disabled="currentPage === totalPages || loading"
              >
                下一页
              </button>
            </div>
          </section>
        </div>
      </div>
    </main>

    <Footer />
    <BackTop :visible="showTop" @click="toTop" />
  </div>
</template>

<script>
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
import BackTop from '@/components/BackTop.vue'
import product from "../system/Product.vue";
import api from '@/api/request'
export default {
  name: 'CoffeeOrigin',
  components: { Header, Footer, BackTop },
  data () {
    return {
      showTop: false,
      currentOrigin: 'all', // 当前选中分类（all=全部）
      currentSort: 'recommend',
      currentdescription: '探索来自中国各地的精选咖啡豆，体验不同产区的独特风味特点',
      sortOptions: [
        { label: '推荐', value: 'recommend' },
        { label: '价格从低到高', value: 'asc' },
        { label: '价格从高到低', value: 'desc' },
        { label: '最新上架', value: 'newest' }
      ],
      Products: [], // 当前显示商品
      totalProductCount: 0, // 总商品数
      originCards: [], // 分类列表（带产品数量）
      currentPage: 1, // 当前页码
      pageSize: 6, // 每页条数
      totalPages: 0, // 总页数
      loading: false, // 加载状态
      isSubmitting: false // 收藏按钮提交状态
    }
  },
  created() {
    // 先加载分类（带产品数量），再加载默认商品
    this.loadOriginCategories().then(() => {
      this.changearea('all');
    });
  },
  computed: {
    displayedProducts () {
      if (!this.Products.length) return [];
      let sortedProducts = [...this.Products];

      // 匹配后端排序逻辑：recommend=按推荐，asc=价格升序，desc=价格降序，newest=按创建时间降序
      switch (this.currentSort) {
        case 'asc':
          sortedProducts.sort((a, b) => Number(a.price) - Number(b.price));
          break;
        case 'desc':
          sortedProducts.sort((a, b) => Number(b.price) - Number(a.price));
          break;
        case 'newest':
          sortedProducts.sort((a, b) => {
            const timeA = a.created_at ? new Date(a.created_at).getTime() : 0;
            const timeB = b.created_at ? new Date(b.created_at).getTime() : 0;
            return timeB - timeA;
          });
          break;
        case 'recommend':
          // 推荐排序：先推荐（is_recommend=true），再最新
          sortedProducts.sort((a, b) => {
            if (a.is_recommend && !b.is_recommend) return -1;
            if (!a.is_recommend && b.is_recommend) return 1;
            return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
          });
          break;
        default:
          break;
      }
      return sortedProducts;
    },
    currentTitle () {
      if (this.currentOrigin === 'all') {
        return '全部咖啡产品';
      }
      const category = this.originCards.find(c => c.id === this.currentOrigin);
      return category ? category.name : '全部咖啡产品';
    },
  },
  mounted () {
    window.addEventListener('scroll', this.handleScroll)
  },
  destroyed () {
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    // 加入购物车（原逻辑不变）
    async addToCart(product) {
      if (this.$store.getters['user/isVisitor']) {
        this.$store.commit('user/SET_REDIRECT_PATH', this.$route.path);
        return this.$confirm(
          '您还暂未登录，无法购买商品，是否前往登录？',
          '提示',
          { confirmButtonText: '是', cancelButtonText: '否', type: 'warning' }
        ).then(() => {
          this.$router.push('/login');
        }).catch(() => {
          this.$message.info('已取消登录');
        });
      }

      try {
        await api.post('/cart', {
          product_id: product.id,
          product_type: 'coffee',
          quantity: 1
        })
        this.$message.success("已成功添加至购物车");
        window.location.reload();
      } catch (e) {
        console.error('添加购物车失败：', e.response?.data);
        this.$message.error(e?.response?.data?.detail || '添加购物车失败，请稍后再试');
      }
    },
    // 加入收藏（原逻辑不变）
    async addTofavorite(product) {
      this.isSubmitting = true;
      try {
        await api.post('/favorite/add', {
          product_id: product.id,
          product_type: 'coffee',
        })
        this.$message.success("已成功添加至收藏");
      } catch (e) {
        console.error('添加收藏失败:', e);
        let errorMsg = "添加收藏失败，请稍后再试";
        if (e.response?.status === 400 || e.response?.status === 500) {
          try {
            const data = typeof e.response.data === "string"
              ? JSON.parse(e.response.data)
              : e.response.data;
            errorMsg = data.detail || data.error || errorMsg;
          } catch (parseError) {
            errorMsg = e.response.data || errorMsg;
          }
        }
        this.$message.warning(errorMsg);
      } finally {
        this.isSubmitting = false;
      }
    },
    // 点击产地卡片切换分类
    selectOrigin (id) {
      this.changearea(id);
      const target = document.querySelector('.product-area');
      if (target) target.scrollIntoView({ behavior: 'smooth' });
    },
    // 核心修复：切换分类（调用后端search接口，支持分类筛选+分页）
    changearea(categoryId) {
      this.currentOrigin = categoryId;
      this.currentPage = 1; // 切换分类重置为第1页

      // 更新分类描述
      if (categoryId === 'all') {
        this.currentdescription = '探索来自中国各地的精选咖啡豆，体验不同产区的独特风味特点';
      } else {
        const currentCat = this.originCards.find(card => card.id === categoryId);
        this.currentdescription = currentCat?.description || `来自${currentCat?.name}的精选咖啡豆，风味独特`;
      }

      // 加载当前分类的商品（调用后端search接口，传分类参数）
      this.loadCoffeeProductsByCategory(categoryId);
    },
    // 滚动监听
    handleScroll () {
      this.showTop = window.scrollY > 300;
    },
    // 核心修复1：加载分类列表（调用后端分类接口，获取分类+对应产品数量）
    async loadOriginCategories() {
      try {
        const res = await this.$axios.get("http://127.0.0.1:8000/coffeeCategory/");
        const categories = Array.isArray(res.data) ? res.data : res;

        // 为每个分类添加产品数量（调用后端by_category接口统计）
        const categoriesWithCount = await Promise.all(
          categories.map(async (cat) => {
            const productRes = await this.$axios.get(`http://127.0.0.1:8000/coffeeProduct/by_category/${cat.id}`);
            return {
              ...cat,
              productCount: productRes.data?.length || 0 // 分类下产品数量
            };
          })
        );

        this.originCards = categoriesWithCount;
        // 统计全部产品数量
        this.totalProductCount = categoriesWithCount.reduce((total, cat) => total + cat.productCount, 0);
        return categoriesWithCount;
      } catch (error) {
        console.error("分类加载失败：", error);
        this.originCards = [];
        this.totalProductCount = 0;
      }
    },
    // 核心修复2：加载分类商品（调用后端search接口，支持分类+分页）
    loadCoffeeProductsByCategory(categoryId) {
      this.loading = true;
      // 后端search接口参数：
      // category_id：0=不筛选，其他=分类ID；page=页码；limit=每页条数
      const params = {
        page: this.currentPage,
        limit: this.pageSize,
        category_id: categoryId === 'all' ? 0 : categoryId, // 全部传0，其他传分类ID
        is_puton: 'true' // 只显示上架商品（后端咖啡商品用is_puton字段）
      };

      return this.$axios.get('http://127.0.0.1:8000/coffeeProduct/search', { params })
        .then(res => {
          console.log(`分类${categoryId}商品数据：`, res.data);
          const { coffee_products, pagination } = res.data || {};

          // 格式化商品数据（匹配后端返回字段）
          this.Products = coffee_products || [];
          // 更新分页信息（后端pagination字段包含total/total_pages）
          this.totalProductCount = pagination?.total || 0;
          this.totalPages = pagination?.total_pages || 0;
          return this.Products;
        })
        .catch(err => {
          console.error(`加载分类${categoryId}商品失败：`, err);
          this.Products = [];
          this.totalProductCount = 0;
          this.totalPages = 0;
          this.$message.error('商品加载失败，请稍后再试');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 上一页（关联当前分类）
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.loadCoffeeProductsByCategory(this.currentOrigin);
      }
    },
    // 下一页（关联当前分类）
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.loadCoffeeProductsByCategory(this.currentOrigin);
      }
    },
    // 跳转到指定页（关联当前分类）
    goToPage(page) {
      if (page >= 1 && page <= this.totalPages && page !== this.currentPage) {
        this.currentPage = page;
        this.loadCoffeeProductsByCategory(this.currentOrigin);
      }
    },
    // 返回顶部
    toTop () {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    },
    // 星级评分样式
    starCls (i, score) {
      const realScore = Number(score) || 0;
      return i <= realScore
        ? 'fa fa-star'
        : (i - 0.5 <= realScore ? 'fa fa-star-half-o' : 'fa fa-star-o');
    }
  }
}
</script>

<style scoped>
/* 全局变量 */
:root {
  --primary: #8B5A2B;
  --secondary: #D2B48C;
  --light: #F5F5DC;
  --dark: #3E2723;
  --radius: 12px;
  --shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  --shadow-lg: 0 10px 25px rgba(0, 0, 0, 0.12);
}
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 16px;
}
.breadcrumb {
  background: #fff;
  border-bottom: 1px solid #e5e7eb;
  font-size: 14px;
  color: #6b7280;
  padding: 12px 0;
}
.breadcrumb .link {
  color: var(--primary);
  text-decoration: none;
}
.breadcrumb .sep {
  margin: 0 8px;
}
.main {
  flex: 1;
  padding: 24px 0 40px;
  background-color: #faf8f5;
}
.page-title {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 24px;
  color: #111;
  text-align: center;
}

/* 产地卡片 */
.origin-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
}
.origin-card {
  position: relative;
  border-radius: var(--radius);
  overflow: hidden;
  box-shadow: var(--shadow);
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
}
.origin-card:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-lg);
}
.card-overlay {
  position: absolute;
  inset: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
  z-index: 1;
}
.card-content {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 16px;
  color: #fff;
  z-index: 2;
}
.card-content h3 {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

/* 两栏布局 */
.main-content {
  display: grid;
  grid-template-columns: 1fr;
  gap: 24px;
}
@media (min-width: 1024px) {
  .main-content {
    grid-template-columns: 260px 1fr;
  }
}

/* 左侧筛选面板 */
.filter-panel {
  background: #fff;
  border-radius: var(--radius);
  box-shadow: var(--shadow);
  padding: 20px;
  position: sticky;
  top: 80px;
  align-self: start;
}
.filter-section h3 {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 8px;
  color: #333;
}
.filter-btn {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 8px 12px;
  margin-bottom: 8px;
  border-radius: 6px;
  background: #f8f8f8;
  border: none;
  font-size: 14px;
  color: #555;
  cursor: pointer;
  transition: all 0.2s;
}
.filter-btn:hover {
  background: #f0f0f0;
}
.filter-btn.active {
  background: var(--primary);
  color: #fff;
}
.filter-btn .badge {
  background: #e0e0e0;
  color: #666;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
}
.filter-btn.active .badge {
  background: #fff;
  color: var(--primary);
}

/* 右侧商品区域 */
.product-area {
  background: #fff;
  border-radius: var(--radius);
  box-shadow: var(--shadow);
  padding: 24px;
}
.intro-bar {
  margin-bottom: 24px;
}
.intro-bar h2 {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 8px;
  color: #333;
}
.intro-bar .desc {
  font-size: 14px;
  color: #666;
  margin: 0 0 16px;
  line-height: 1.5;
}
.sort-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}
.sort-bar span {
  font-size: 14px;
  color: #666;
}
.sort-btn {
  padding: 6px 12px;
  border-radius: 6px;
  background: #f8f8f8;
  border: none;
  font-size: 14px;
  color: #555;
  cursor: pointer;
  transition: all 0.2s;
}
.sort-btn:hover {
  background: #f0f0f0;
}
.sort-btn.active {
  background: var(--primary);
  color: #fff;
}
.spacer {
  flex: 1;
}
.view-btn {
  width: 36px;
  height: 36px;
  border-radius: 6px;
  background: #f8f8f8;
  border: none;
  color: #666;
  cursor: pointer;
  transition: all 0.2s;
}
.view-btn:hover, .view-btn.active {
  background: var(--primary);
  color: #fff;
}

/* 商品网格 */
.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
}
.product-card {
  border-radius: var(--radius);
  overflow: hidden;
  box-shadow: var(--shadow);
  transition: transform 0.3s, box-shadow 0.3s;
}
.product-card:hover {
  transform: translateY(-3px);
  box-shadow: var(--shadow-lg);
}
.img-box {
  position: relative;
}
.product-img {
  width: 100%;
  object-fit: cover;
}
.badge {
  position: absolute;
  top: 10px;
  left: 10px;
  padding: 4px 8px;
  font-size: 12px;
  border-radius: 4px;
  color: #fff;
  z-index: 1;
}
.badge.featured {
  background: var(--primary);
}
.hover-box {
  position: absolute;
  inset: 0;
  background: rgba(0, 0, 0, 0.2);
  opacity: 0;
  transition: opacity 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  z-index: 1;
}
.product-card:hover .hover-box {
  opacity: 1;
}
.icon-btn {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  background: #fff;
  color: #333;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}
.icon-btn:hover {
  background: var(--primary);
  color: #fff;
}
.card-body {
  padding: 16px;
}
.meta {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
}
.name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #333;
  transition: color 0.2s;
}
.name:hover {
  color: var(--primary);
}
.rating {
  font-size: 12px;
  color: #ffb400;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 2px;
}
.rating span {
  color: #999;
  margin-left: 4px;
}
.price-row {
  display: flex;
  align-items: center;
  gap: 8px;
}
.price {
  font-size: 16px;
  font-weight: 600;
  color: #ef4444;
}
.original {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}

/* 分页样式 */
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}
.pagination-btn, .pagination-page {
  padding: 6px 12px;
  border-radius: 6px;
  border: 1px solid #e0e0e0;
  background: #fff;
  color: #666;
  cursor: pointer;
  transition: all 0.2s;
}
.pagination-btn:hover, .pagination-page:hover {
  border-color: var(--secondary);
  color: var(--primary);
}
.pagination-page.active {
  background: var(--primary);
  border-color: var(--primary);
  color: #fff;
}
.pagination-btn:disabled {
  cursor: not-allowed;
  opacity: 0.5;
  border-color: #f0f0f0;
  color: #ccc;
  background: #f8f8f8;
}

/* 空数据/加载中提示 */
.empty-tip, .loading-tip {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 0;
  font-size: 16px;
  color: #666;
}
.loading-tip {
  color: var(--primary);
}

/* router-link 样式重置 */
/deep/ .router-link {
  color: inherit;
  text-decoration: none;
}
/deep/ .router-link:active,
/deep/ .router-link:focus {
  color: inherit;
  outline: none;
}
</style>